<template>
  <div class="container mt-5">
    <div class="row mb-4">
      <div class="col-12">
        <h2 class="mb-3"><i class="fas fa-landmark mr-2"></i>文化遗产管理</h2>
        <div class="d-flex justify-content-between align-items-center mb-3">
          <div class="search-container">
            <div class="search-box">
              <input type="text" v-model="searchQuery" class="search-input" placeholder="搜索名称、类型或地点...">
              <button class="search-btn" @click="searchHeritage">
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>
          <router-link to="/heritage/add" class="btn btn-primary">
            <i class="fas fa-plus mr-1"></i>添加文化遗产
          </router-link>
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-hover">
                <thead>
                  <tr>
                    <th>名称</th>
                    <th>类型</th>
                    <th>地点</th>
                    <th>年代</th>
                    <th>保护级别</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in heritageList" :key="item.id">
                    <td>{{ item.name }}</td>
                    <td>{{ item.type }}</td>
                    <td>{{ item.location }}</td>
                    <td>{{ item.year }}</td>
                    <td>{{ item.protectionLevel }}</td>
                    <td>
                      <router-link :to="`/heritage/edit/${item.id}`" class="btn btn-sm btn-warning mr-2">
                        <i class="fas fa-edit"></i>
                      </router-link>
                      <button @click="deleteHeritage(item.id)" class="btn btn-sm btn-danger">
                        <i class="fas fa-trash"></i>
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listHeritage, searchHeritage, deleteHeritage } from '@/api/api';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'HeritageList',
  data() {
    return {
      heritageList: [],
      searchQuery: '',
      loading: false
    }
  },
  methods: {
    async fetchHeritageList() {
      this.loading = true;
      try {
        console.log('开始获取文化遗产列表...');
        const response = await listHeritage();
        console.log('获取到的数据:', response);
        
        // 处理响应数据
        if (response && response.status === 200) {
          // 如果响应中有 data 字段，则使用 data 字段
          if (response.data !== undefined) {
            // 检查 data 是否是数组
            if (Array.isArray(response.data)) {
              this.heritageList = response.data;
            } 
            // 检查是否是分页数据
            else if (response.data.records && Array.isArray(response.data.records)) {
              this.heritageList = response.data.records;
            }
            // 其他情况，直接使用 data
            else {
              this.heritageList = [response.data];
            }
          } 
          // 如果响应中没有 data 字段，则直接使用响应
          else if (Array.isArray(response)) {
            this.heritageList = response;
          } else {
            console.warn('返回的数据格式不符合预期:', response);
            this.heritageList = [];
          }
        } else {
          console.warn('返回的响应状态码不是200:', response);
          this.heritageList = [];
        }
        
        console.log('处理后的列表数据:', this.heritageList);
        
        if (this.heritageList.length === 0) {
          ElMessage.info('暂无文化遗产数据');
        }
      } catch (error) {
        console.error('获取文化遗产列表失败:', error);
        ElMessage.error('获取文化遗产列表失败: ' + (error.response?.data?.message || error.message));
      } finally {
        this.loading = false;
      }
    },
    async searchHeritage() {
      try {
        this.loading = true;
        
        if (!this.searchQuery || !this.searchQuery.trim()) {
          // 如果搜索框为空，获取所有文化遗产
          await this.fetchHeritageList();
          return;
        }
        
        console.log('执行搜索，关键词:', this.searchQuery);
        const response = await searchHeritage(this.searchQuery.trim());
        
        // 处理响应数据
        if (response && response.data) {
          // 如果响应中有 data 字段，则使用 data 字段
          if (Array.isArray(response.data)) {
            this.heritageList = response.data;
          } else if (response.data.records && Array.isArray(response.data.records)) {
            this.heritageList = response.data.records;
          } else {
            this.heritageList = [response.data];
          }
        } else if (Array.isArray(response)) {
          // 如果响应直接是数组
          this.heritageList = response;
        } else {
          console.warn('返回的数据格式不符合预期:', response);
          this.heritageList = [];
        }
        
        console.log('处理后的搜索结果:', this.heritageList);
        
        if (this.heritageList.length === 0) {
          ElMessage.info('未找到匹配的文化遗产');
        }
      } catch (error) {
        console.error('搜索文化遗产失败:', error);
        ElMessage.error('搜索失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    async deleteHeritage(id) {
      try {
        await ElMessageBox.confirm('确定要删除该文化遗产吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await deleteHeritage(id);
        ElMessage.success('删除成功');
        this.fetchHeritageList();
      } catch (error) {
        if (error !== 'cancel') {  // 如果不是用户取消操作
          console.error('删除文化遗产失败:', error);
          ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
        }
      }
    },
    // 添加一个测试方法，用于测试API是否正常工作
    async testApi() {
      try {
        const response = await apiClient.get('/api/feign/heritage');
        console.log('测试API响应:', response);
      } catch (error) {
        console.error('测试API失败:', error);
      }
    },
    getProtectionLevelClass(level) {
      const levelMap = {
        '国家级': 'protection-level-national',
        '省级': 'protection-level-provincial',
        '市级': 'protection-level-municipal',
        '县级': 'protection-level-county'
      };
      return levelMap[level] || '';
    }
  },
  created() {
    this.fetchHeritageList();
  }
}
</script>

<style scoped>
/* 卡片样式 */
.card {
  border: none;
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
}

/* 卡片头部样式 */
.card-header {
  background-color: #2c3e50;
  color: white;
  border-bottom: none;
  padding: 1.5rem 1.5rem 1rem;
  border-radius: 15px 15px 0 0;
}

.card-header h2 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.card-header i {
  color: #3498db;
  margin-right: 0.5rem;
  font-size: 1.2rem;
}

/* 添加按钮样式 */
.btn-primary {
  background-color: #3498db;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.btn-primary:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
}

/* 表格样式 */
.table {
  margin-bottom: 0;
  background: white;
}

.table th {
  background-color: #f8f9fa;
  border: none;
  font-weight: 600;
  color: #333;
  padding: 1rem;
  font-size: 0.95rem;
}

.table td {
  border: none;
  vertical-align: middle;
  padding: 1rem;
  font-size: 0.95rem;
  color: #333;
}

.table tr:hover {
  background-color: rgba(52, 152, 219, 0.05);
}

/* 操作按钮样式 */
.btn-sm {
  padding: 0.4rem 0.8rem;
  font-size: 0.875rem;
  border-radius: 6px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.btn-sm i {
  font-size: 0.875rem;
}

.btn-warning {
  background-color: #f1c40f;
  border: none;
}

.btn-danger {
  background-color: #e74c3c;
  border: none;
}

.btn-warning:hover,
.btn-danger:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

/* 搜索框样式 */
.search-container {
  max-width: 400px;
  margin-bottom: 1rem;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.search-box:hover {
  border-color: #3498db;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  padding: 0.75rem 1rem;
  font-size: 0.95rem;
  background: transparent;
  color: #333;
  transition: all 0.3s ease;
}

.search-input:focus {
  box-shadow: none;
  border: none;
  outline: none;
  background: white;
}

.search-btn {
  background-color: #3498db;
  border: none;
  color: white;
  padding: 0.75rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 500;
}

.search-btn:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
}

.search-btn i {
  font-size: 1rem;
}

.search-box::before {
  content: '';
  position: absolute;
  left: 1rem;
  width: 20px;
  height: 20px;
  background: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 20 20'%3E%3Cpath fill='%236c757d' d='M8 16a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm.93-9.41a3 3 0 0 0-4.24-4.24l-2.15 2.15a4 4 0 0 1 5.66 5.66l.75-.75A3 3 0 0 0 8 9.41z'/%3E%3C/svg%3E") no-repeat center center;
  background-size: contain;
  opacity: 0.5;
}

@media (max-width: 768px) {
  .search-container {
    width: 100%;
    margin-bottom: 1rem;
  }
  
  .search-input,
  .search-btn {
    font-size: 0.9rem;
    padding: 0.65rem 0.85rem;
  }
  
  .search-btn i {
    font-size: 0.95rem;
  }
}

/* 保护级别颜色 */
.protection-level {
  padding: 0.35rem 0.75rem;
  border-radius: 12px;
  font-size: 0.875rem;
  font-weight: 500;
}

.protection-level-national {
  background-color: #3498db;
  color: white;
}

.protection-level-provincial {
  background-color: #2ecc71;
  color: white;
}

.protection-level-municipal {
  background-color: #f1c40f;
  color: #333;
}

.protection-level-county {
  background-color: #95a5a6;
  color: white;
}

/* 间距类 */
.mr-2 {
  margin-right: 0.75rem;
}

.mr-1 {
  margin-right: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header h2 {
    font-size: 1.5rem;
  }
  
  .btn-primary {
    padding: 0.6rem 1.2rem;
    font-size: 0.9rem;
  }
  
  .table th,
  .table td {
    padding: 0.8rem;
    font-size: 0.875rem;
  }
}
</style>
